package com.eco.fanliapp.controller.app;

import com.alipay.api.domain.OrderDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.common.constant.WxWithdrawal;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppNewsLog;
import com.eco.fanliapp.entity.AppOrderDetail;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SyUserWxContrast;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.AppWxWithdrawalUtils.WXPayRequest;
import com.eco.fanliapp.utils.AppWxWithdrawalUtils.WXPayUtil;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.UUIDUtils;
import com.eco.fanliapp.vo.AppRequestParams.WxPayRequestParams;
import com.eco.fanliapp.vo.wechat.menu.CommonButton;
import com.eco.fanliapp.vo.wechat.menu.Menu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuchao
 * @create 2019-08-07 15:14
 */
@Controller
@RequestMapping("/wx")
@Slf4j
public class WxTestController extends BaseController {

	@Autowired
	private ISyUserWxContrastService syUserWxContrastService;
	@Autowired
	private IAppNewsLogService appNewsLogService;
	@Autowired
	private WXPayRequest wxPayRequest;
	@Autowired
	private IAppWxWithdrawalService appWxWithdrawalService;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private IAppNewsLogService iAppNewsLogService;
	@Autowired
	private IAppUserRedRewardService IAppUserRedRewardService;
	@Autowired
	private IAppUserService appUserService;
	@Autowired
	private ITaoBaoOrderService taoBaoOrderService;
	@Autowired
	private ITaoBaoOrderNewService taoBaoOrderNewService;
	@Autowired
	private ISyBlacklistService syBlacklistService;
	@Autowired
	private ISmsService smsService;

	@GetMapping("/testMes")
	@ResponseBody
	public ServerResponse testMes(String phone,String time) {
		String s = smsService.sendSms4(phone, "测试的联盟");
		return ServerResponse.createBySuccessMessage(s);
	}
	@GetMapping("/test")
	@ResponseBody
	public ServerResponse test(Long userId,String money) {
		QueryWrapper<AppUser> query = new QueryWrapper<>();
		query.eq("user_id",userId);
		List<AppUser> list = appUserService.list(query);
		AppUser appUser = list.get(0);

		AppOrderDetail appOrderDetail = new  AppOrderDetail();
		appOrderDetail.setItemPrice(money);
		IAppUserRedRewardService.addInvitationedMoney(appUser, appOrderDetail);
		return ServerResponse.createBySuccessMessage("推送成功！");
	}
	@GetMapping("/pushMessage")
	@ResponseBody
	public ServerResponse pushMessage(Long userId,int msgType,double money) {
		//iAppNewsLogService.newsType(userId,msgType,BigDecimalUtils.Format(money));
		return ServerResponse.createBySuccessMessage("推送成功！");
	}
	@GetMapping("/addButton")
	@ResponseBody
	public ServerResponse addButton(String accessToken) throws IOException {
		String url = WechatConfig.CREATE_MENU_URL.replace("ACCESS_TOKEN",accessToken);
		String jsonStr = "";
		WeixinUtil.doPostStr(url,jsonStr);
		return null;
	}
	/**
	 * 消息-消息列表接口
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/user/list")
	@ResponseBody
	public ServerResponse getUserList(@RequestParam(defaultValue = "1") Long pageNum , @RequestParam(defaultValue = "20") Long pageSize) {

		String userId = "111";
		String openid = "oPTqx5-7DLNr6Uk96XPTh4TWp8VI";
		String amount = "1";
		//二 ：调用企业支付接口进行提现
		//1.创建微信企业支付请求参数
		WxPayRequestParams wxPayRequestParams;
		try {
			wxPayRequestParams = new WxPayRequestParams();
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage("请求参数错误！");
		}
		//2.填充请求参数
		String partnerTradeNo= creatPartnerTradeNo(Long.parseLong(userId), amount);
		wxPayRequestParams.setAmount(amount);//金额
		wxPayRequestParams.setOpenid(openid);//用户的openid（从用户表中获取）
		//wxPayRequestParams.setRe_user_name("张三");//真实姓名（从用户表中获取）
		wxPayRequestParams.setDesc("省鸭APP提现");//企业付款备注
		wxPayRequestParams.setPartner_trade_no(partnerTradeNo);//订单号
		//3.请求参数转成xml
		String xmlStr;
		try {
			Map map = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(wxPayRequestParams), HashMap.class);
			xmlStr = WXPayUtil.generateSignedXml(map, WxWithdrawal.key);
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage("参数转换错误！");
		}
		log.info("请求微信支付接口参数：{}",xmlStr);
		String uuid = UUIDUtils.getUUID();
		//调用支付接口
		String wxPayResultXml;
		try {
			wxPayResultXml = wxPayRequest.requestWithCert(WxWithdrawal.urlSuffix, uuid, xmlStr, true);
			//wxPayResultXml = getRestTemplate("https://" +WxWithdrawal.doMain + WxWithdrawal.urlSuffix, xmlStr);
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage("支付失败！请求错误");
		}
		log.info("请求微信支付接口结果{}"+wxPayResultXml);
		Map<String, String> stringStringMap = null;
		try {
			stringStringMap = WXPayUtil.xmlToMap(wxPayResultXml);
		} catch (Exception e) {
			log.info("微信结果参数转换异常{}",e.getMessage());
		}
		String return_code = MapUtils.getString(stringStringMap, "return_code");
		String result_code = MapUtils.getString(stringStringMap, "result_code");
		return ServerResponse.createBySuccess("返回结果",result_code);
	}

	/**
	 * 生成商户订单号  年与日时分秒+用户id+金额
	 * @return
	 */
	private String creatPartnerTradeNo(Long userId,String amount){
		StringBuilder stringBuilder = new StringBuilder();
		Long dateStr = DateFormatUtils.dateToString(new Date(), "yyyyMMddHHmm");
		stringBuilder.append(dateStr);
		stringBuilder.append("601982048109");
		stringBuilder.append(5);
		int length = 32 - stringBuilder.toString().length();
		stringBuilder.append(RandomStringUtils.randomNumeric(length));
		return stringBuilder.toString();
	}

   /**
	* 发送消息通知
	* @param messageType
	* @param keyword1Param
	* @param keyword2Param
	* @param keyword3Param
	* @param keyword4Param
	* @return
	* @throws ParseException
	* @throws IOException
	*/
	@GetMapping("/sendCashMessage")
	@ResponseBody
	public  ServerResponse<String> sendCashMessage(String messageType, String keyword1Param,String keyword2Param,String keyword3Param, String keyword4Param) throws ParseException, IOException {

		AppUser u = getAppUser();
		if(null == u) {
			return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
		}
		//获取openId
		QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("union_id",u.getWechatUnionid());
		queryWrapper.eq("enable",true);
		queryWrapper.eq("deleted",false);
		List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);
		SyUserWxContrast contrast = null;
		String openId = "";
		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(listWxContrast)){
			//已经关注公众号，返回提示
			openId = listWxContrast.get(0).getWxOpendId();
		}

		//校验参数
		if(openId==null || "".equals(openId)){
			return ServerResponse.createByErrorMessage("该用户未关注公众号:" +  u.getUserId());
		}
		if(messageType==null){
			return ServerResponse.createByErrorMessage("参数不能为空:" +  messageType);
		}

		String accessTokne = appWxWithdrawalService.getAccessToken();
		//区分消息模板id
		String templateId = "";
		String firstParam = "";
		String remarkParam = "";
		Integer newsType = null;
		if("30001".equals(messageType)){
			templateId = WechatConfig.ARRIVAL_ACCOUNT_TEMPLATE_ID;//提现到账通知
			firstParam = "你好，您已成功提现";
			remarkParam = "现金已成功到账您的微信钱包，详情查看《我》-《钱包》-《零钱明细》";
			newsType = NewsEnumLog.NEWS_ARRIVAL_ACCOUNT.getNewsType();
		}
		if("30002".equals(messageType)){
			templateId = WechatConfig.CHECKOUT_SUCCESS_TEMPLATE_ID;//下单成功提醒
			firstParam = "下单成功";
			remarkParam = "此次帮您节省" + keyword4Param + "元";
			newsType = NewsEnumLog.NEWS_CHECKOUT_SUCCESS.getNewsType();
		}
		if("30003".equals(messageType)){
			templateId = WechatConfig.SUCCESSFUL_DELIVERY_TEMPLATE_ID;//收货成功提醒
			firstParam = "收货成功提醒";
			remarkParam = "您的补贴金额" + keyword4Param + "元";
			newsType = NewsEnumLog.NEWS_SUCCESSFUL_DELIVERY.getNewsType();
		}
		if("30004".equals(messageType)){
			templateId = WechatConfig.FRIENDS_SUCCEED_TEMPLATE_ID;//好友下单成功提醒
			firstParam = "好友下单成功";
			remarkParam = "详情请进入省鸭App中查看";
			newsType = NewsEnumLog.NEWS_FRIENDS_SUCCEED.getNewsType();
		}

		if("30005".equals(messageType)){
			templateId = WechatConfig.INVITE_FRIENDS_TEMPLATE_ID;//邀请好友成功
			firstParam = "邀请好友成功";
			remarkParam = "详情请进入省鸭App中查看";
			newsType = NewsEnumLog.NEWS_INVITE_FRIENDS.getNewsType();
		}

		if("30006".equals(messageType)){
			templateId = WechatConfig.SUBSIDY_ARRIVAL_TEMPLATE_ID;//补贴到账通知
			firstParam = "补贴到账";
			remarkParam = "详情请进入省鸭App中查看";
			newsType = NewsEnumLog.NEWS_SUBSIDY_ARRIVAL.getNewsType();
		}
		if("".equals(templateId)){
			return ServerResponse.createByErrorMessage("传入的模板类型不存在！");
		}
		if(newsType == null){
			return ServerResponse.createByErrorMessage("未匹配到消息类型！");
		}
		//组装数据发送消息
		Map<String, String> map = WeixinUtil.handleMessage(accessTokne,openId, templateId, firstParam, keyword1Param, keyword2Param, keyword3Param, keyword4Param, remarkParam);
		String newsContent = map.get("newsContent");//消息内容
		String aBoolean = map.get("result");//消息结果
		//日志记录
	/*	AppNewsLog log = new AppNewsLog();
		log.setUserId(u.getUserId());
		log.setNewsTitle(firstParam);
		log.setNewsContent(newsContent);
		log.setNewsType(newsType);
		log.setCreateTime(System.currentTimeMillis());
		log.setUpdateTime(System.currentTimeMillis());
		appNewsLogService.save(log);*/

		return ServerResponse.createBySuccess("消息发送结果","true".equals(aBoolean) ? "成功" : "失败");
	}


	@GetMapping("/getAccessToken")
	@ResponseBody
	public ServerResponse<String> getAccessTokenTest() throws IOException {

		String accessToken = appWxWithdrawalService.getAccessToken();
		return ServerResponse.createBySuccess("accessToken返回",accessToken);
	}

	@GetMapping("/test/getAccessToken")
	@ResponseBody
	public ServerResponse<String> getAccessToken() throws IOException {
		String accessToken = WeixinUtil.getAccessToken();
		redisTemplate.opsForValue().set("access_token",accessToken, 3600, TimeUnit.SECONDS);
		return ServerResponse.createBySuccess("accessToken返回",accessToken);
	}

	@GetMapping("/testCreateMenu")
	@ResponseBody
	public ServerResponse testCreateMenu() throws Exception {
		//1.准备好请求参数
//		String accessToken = appWxWithdrawalService.getAccessToken();
		String accessToken ="24_4-tD9b_aG1-bKP9QSOuP-APj1u_8ySaYC2uFdND5Ys8cr-mfdqd1-i3TkXyIWaPi8N-rbughjYLl2hCe6NPibVESl7TNflEEpEqkUcgoaM1a5pekjO8wT8JSNB-MroSc9mFkMmv_VOXakJ8LMMXbABAYYJ";
		Menu menu=getMenu();

		//2.调用接口，执行请求
		return  appWxWithdrawalService.createMenu(menu, accessToken);
	}


	/**
	 * @desc ：辅助1.组装菜单数据
	 *
	 * @return Menu
	 */
	private static Menu getMenu() {
		CommonButton btn11 = new CommonButton();
		btn11.setName("提现");
		btn11.setType("click");
		btn11.setKey("11_Withdraw");

		Menu menu = new Menu();
		menu.setButton(new CommonButton[]{btn11});

		return menu;
	}

	@GetMapping("/testReturn")
	@ResponseBody
	public ServerResponse testReturn() throws Exception {
		String toUserName = "gh_613b2685289b";
		String fromUserName = "orFK5wBZ1XP8Kje7wq6oVZNByBWQ";
		String msgId = null;
		String   message = appWxWithdrawalService.getResponseMessage(toUserName, fromUserName, msgId);
		return  ServerResponse.createBySuccessMessage(message);
	}

	@GetMapping("/testHandle")
	@ResponseBody
	public ServerResponse testHandle(Long userId, Long tradeId) throws Exception {
		Object obj = taoBaoOrderNewService.testHandle(userId,tradeId);
		log.info(obj.toString());
		return null;
	}

	@GetMapping("/testCheckUser")
	@ResponseBody
	public ServerResponse testCheckUser(Long userId) throws Exception {
		Boolean aBoolean = syBlacklistService.verifyUserAgreement(userId);
		return ServerResponse.createBySuccess(aBoolean);
	}
}
